package itbour.onetouchshow.activity.login;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import itbour.onetouchshow.utils.L_;

/**
 * ================================================
 * 作    者：顾修忠-guxiuzhong@youku.com/gfj19900401@163.com
 * 版    本：
 * 创建日期：2017/3/2-下午7:06
 * 描    述：
 * 修订历史：
 * ================================================
 */

public class VideoExtractFrameAsyncUtils {

    public static boolean stop = false;
    private Handler mHandler;
    private int extractW;
    private int extractH;

    public VideoExtractFrameAsyncUtils(int extractW, int extractH, Handler mHandler) {
        this.mHandler = mHandler;
        this.extractW = extractW;
        this.extractH = extractH;
    }

    /**
     * 设置固定的宽度，高度随之变化，使图片不会变形
     *
     * @param bm Bitmap
     * @return Bitmap
     */
    private static Bitmap scaleImage(Bitmap bm, int extractW, int extractH) {
        if (bm == null) {
            return null;
        }
        int width = bm.getWidth();
        int height = bm.getHeight();

        L_.e("scaleImage  ----width>" + width);
        L_.e("scaleImage  ----height>" + height);

        if (extractW > width) {
            extractW = width;
        }
        if (extractH > height) {
            extractH = height;
        }
        float scaleWidth = extractW * 1.0f / width;
        float scaleHeight = extractH * 1.0f / height;

        if (scaleWidth > width) {
            scaleWidth = width;
        }
        if (scaleHeight > height) {
            scaleHeight = height;
        }

        float max = Math.max(scaleWidth, scaleHeight);
        Matrix matrix = new Matrix();
        matrix.postScale(max, max);

        L_.e("scaleImage  ----extractH>" + extractH);
        L_.e("scaleImage  ----extractW>" + extractW);
        Bitmap newBm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
                true);
        L_.e("scaleImage  ----width>" + newBm.getWidth());
        L_.e("scaleImage  ----height>" + newBm.getHeight());
        if (!bm.isRecycled()) {
            bm.recycle();
            bm = null;
        }
        return newBm;
    }

    public void getVideoThumbnailsInfoForEdit(String videoPath, String OutPutFileDirPath, long startPosition, long endPosition, int thumbnailsCount) {
        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
        metadataRetriever.setDataSource(videoPath);
        long interval = (endPosition - startPosition) / (thumbnailsCount - 1);
        stop = false;
        for (int i = 0; i < thumbnailsCount; i++) {
            if (stop) {
                Log.d("ExtractFrame", "-------ok-stop-stop-->>>>>>>>>");
                metadataRetriever.release();
                break;
            }
            long time = startPosition + interval * i;
            if (i == thumbnailsCount - 1) {
//                if (interval > 1000) {
//                    String path = extractFrame(metadataRetriever, endPosition - 800, OutPutFileDirPath);
//                    sendAPic(path, endPosition - 800);
//                } else {
//                    String path = extractFrame(metadataRetriever, endPosition, OutPutFileDirPath);
//                    sendAPic(path, endPosition);
//                }
                Bitmap bitmap = metadataRetriever.getFrameAtTime((long) (i * 1000 * 1000), MediaMetadataRetriever.OPTION_CLOSEST);

                //sendAPic(bitmap, time);
            } else {
                //  String path = extractFrame(metadataRetriever, time, OutPutFileDirPath);
                //sendAPic(path, time);
                Bitmap bitmap = metadataRetriever.getFrameAtTime((long) (i * 1000 * 1000), MediaMetadataRetriever.OPTION_CLOSEST);
                //  sendAPic(bitmap, time);
            }
        }

        //metadataRetriever.release();
    }

    /**
     * java 原生抽帧
     *
     * @param input      要抽帧的视频路径
     * @param begin      开始抽帧时间
     * @param end        结束抽帧时间
     * @param timeMargin 抽帧间隔
     * @param width      抽帧最大宽
     * @param height     抽帧最大高
     * @return result map
     * <p>
     * {
     * "code" : 0, 0 标记成功, 非零标记失败
     * "thumbs":[] bitmap 数组
     * }
     */
    public List<Bitmap> javaGetVideoFrames(int mType, String input, double begin, double end, double timeMargin, int maxSize, int width, int height) {
        // 构建返回值并异常保护
        // HashMap<String, Object> result = new HashMap<>();
        // result.put("code", "-1");
        L_.e("抽取  maxSize" + maxSize);
        if (null == input || input.length() <= 2) return new ArrayList<>();
        if (end <= begin) return new ArrayList<>();
        begin = begin <= 0 ? 0 : begin;
        timeMargin = timeMargin <= 0 ? 0 : timeMargin;
        // 读取视频信息
        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();

        //如果是网络路径
        if (input.startsWith("http") || input.startsWith("https")) {
            metadataRetriever.setDataSource(input, new HashMap());
        } else {
            metadataRetriever.setDataSource(input);
        }
        // Double.parseDouble(metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));
        double totalTime = Double.parseDouble(metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
        end = end < totalTime ? end : totalTime;
        // end = end < totalTime ? end : totalTime;
        // 循环取图并返回数据
        List<Bitmap> thumbs = new ArrayList<>();
        //if (begin < end) return thumbs;
        //result.put("thumbs", thumbs);
        //int i = 500 * 1000; i <= videoView.getDuration() * 1000; i += 1000 * 1000
        stop = false;
        for (double i = begin / 1000; i < end / 1000; i += timeMargin) {
            if (stop) {
                Log.d("ExtractFrame", "-------ok-stop-stop-->>>>>>>>>");
                metadataRetriever.release();
                return thumbs;
            }
            long l = System.currentTimeMillis();
            Bitmap bitmap = metadataRetriever.getFrameAtTime((long) (i * 1000 * 1000), MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
            Bitmap bitmap1 = scaleImage(bitmap, width, height);
            sendAPic(bitmap1, 0);
            // L_.e("System.currentTimeMillis()" + (System.currentTimeMillis() - l) / 1000.0 + "S");
            if (i > maxSize) {
                metadataRetriever.release();
                break;
            }
        }
        return thumbs;
    }

    /**
     * 成功一张add一张
     *
     * @param time time
     */
    private void sendAPic(Bitmap thumb, long time) {
        // VideoEditInfo info = new VideoEditInfo();
        // info.path = path;
        // info.time = time;
        Message msg = mHandler.obtainMessage(ExtractFrameWorkThread.MSG_SAVE_SUCCESS);
        msg.obj = thumb;
        mHandler.sendMessage(msg);

    }

//    public void stopExtract() {
//        stop = true;
//    }
}
